
"""
Copyright 2009 Andrew T. Barker

This file is part of Second Budget.

Second Budget is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

Second Budget is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with Second Budget, in the file LICENSE.  If not, see 
<http://www.gnu.org/licenses/>.
"""

# a GUI to review the screenshots from secondbudget

from Tkinter import *
import ImageTk, Image
import glob,datetime,os
import readlog,sbconfig

sbc = sbconfig.SBConfig()

ssdir = sbc.directory
stampfmt = sbc.stampfmt

logfile = sbc.logfile
logging = sbc.logging

def getstamp(thestring):
    parsed = thestring.split("/")
    prefixlength = 2 # should look this up in config or something
    part = parsed[-1][prefixlength:-4]
    return datetime.datetime.strptime(part,stampfmt)

class ScoredScreenshot:

    def __init__(self,stamp=None,score=0):
        # self.filename = filename
        # self.stamp = datetime.datetime.strptime(self.filename,stampfmt)
        # self.stamp = getstamp(self.filename)
        self.stamp = stamp
        self.score = score

    def asstring(self):
        # out = self.filename + ","
        out = self.stamp.strftime(stampfmt) + ","
        out = out + str(self.score) + "\n"
        return out

    def fromstring(self,thestring):
        parsed = thestring.split(",")
        # self.filename = parsed[0]
        self.stamp = datetime.datetime.strptime(parsed[0],"%d%b%Yat%H.%M")
        # self.stamp = getstamp(self.filename)
        self.score = int(parsed[1])

class SBScore:

    def __init__(self, master):        
        # general data
        # a = datetime.datetime.now()        
        # self.filelist = glob.glob(ssdir + "ss" + a.strftime("%d%b%Y") + "*")        
        ld = readlog.LogData()
        laststamp = ld.getlaststamp()

        # eventually I want filelist and its iterator to be a separate class
        self.filelist = []
        prelist = glob.glob(ssdir + "ss*")
        for file in prelist:
            stamp = getstamp(file)
            if stamp > laststamp: self.filelist.append(file)
            
        self.filelist.sort()
        self.fileit = iter(self.filelist)                                  

        self.pluses = 0
        self.zeros = 0
        self.minuses = 0                                  

        # make GUI                                  
        self.frame = Frame(master)                                  
        self.frame.pack()                                  

        self.height = 720
        self.width = 1400                                  
        
        self.canvas = Canvas(self.frame, width=self.width, height=self.height)        
        self.canvas.pack(side=TOP)

        controlframe = Frame(self.frame, width=self.width, height=100)
        controlframe.pack(side=BOTTOM)

        self.minusone = Button(controlframe, text="-1", command=self.minusclick)
        self.minusone.pack(side=LEFT)
        self.zero = Button(controlframe, text="0", command=self.zeroclick)
        self.zero.pack(side=LEFT)
        self.plusone = Button(controlframe, text="+1", command=self.plusclick)
        self.plusone.pack(side=LEFT)

        self.nextpic(0,False)                                  

    def nextpic(self,score=0,log=True):
        if logging and log:
            b = ScoredScreenshot(getstamp(self.np),score)
            fd = open(logfile,"a")
            fd.write(b.asstring())
            fd.close()
        try:
            self.np = self.fileit.next()
            imgobj = Image.open(self.np)
            # there should be a better way to make a prettier reduced-size image
            imgobj.thumbnail((self.width,self.height))
            img = ImageTk.PhotoImage(imgobj)
            item = self.canvas.create_image(2,2,anchor=NW,image=img)
            self.canvas.image = img
        except StopIteration:
            self.finish()

    def minusclick(self):
        self.minuses = self.minuses + 1
        self.nextpic(-1)

    def zeroclick(self):
        self.zeros = self.zeros + 1
        self.nextpic(0)
    
    def plusclick(self):
        self.pluses = self.pluses + 1
        self.nextpic(1)

    def finish(self):
        print "good: %d" % self.pluses
        print "bad: %d" % self.minuses
        print "indifferent: %d" % self.zeros
        print "score: %f" % (float(self.pluses) / float((self.pluses + self.minuses)))
        self.frame.quit()

def convertimages():
    # use filelist and its iterator, exctracted from class above
    # use gimp and try.scm, try.sh to convert .xwd to .jpg
    pass

def main():
    # if sbconfig.screenshottool == "xwd": convertimages()
    root = Tk()
    q = SBScore(root)
    root.mainloop()

if __name__ == "__main__":
    main()
